from os_ken.base import app_manager
from os_ken.controller.handler import set_ev_cls
from os_ken.services.protocols.bgp import application as bgp_application

from os_ken.controller import ofp_event
from os_ken.controller.handler import CONFIG_DISPATCHER, MAIN_DISPATCHER
from os_ken.controller.handler import set_ev_cls
from os_ken.ofproto import ofproto_v1_3
from os_ken.lib.packet import packet
from os_ken.lib.packet import ethernet
from os_ken.lib.packet import ether_types


class MyBGPApp(app_manager.OSKenApp):
    _CONTEXTS = {
        "os_kenbgpspeaker": bgp_application.OSKenBGPSpeaker,
    }
    OFP_VERSIONS = [ofproto_v1_3.OFP_VERSION]

    def __init__(self, *args, **kwargs):
        super(MyBGPApp, self).__init__(*args, **kwargs)

        # Stores "os_ken.services.protocols.bgp.application.OSKenBGPSpeaker"
        # instance in order to call the APIs of
        # "os_ken.services.protocols.bgp.bgpspeaker.BGPSpeaker" via
        # "self.app.speaker".
        # Please note at this time, "BGPSpeaker" is NOT instantiated yet.
        self.app = kwargs["os_kenbgpspeaker"]
        self.mac_to_port = {}

    @set_ev_cls(bgp_application.EventBestPathChanged)
    def _best_patch_changed_handler(self, ev):
        self.logger.info(
            "_best_patch_changed_handler: %s/%s", ev.path.nlri.addr, ev.path.nlri.length
        )
        # self.logger.info("_best_patch_changed_handler: %s", ev.path.source)
        # self.logger.info(
        #     "_best_patch_changed_handler: %s", ev.path._path_attr_map[2].value[0][0]
        # )
        pass

    @set_ev_cls(bgp_application.EventAdjRibInChanged)
    def _adj_rib_in_changed_handler(self, ev):
        self.logger.info(
            "_adj_rib_in_changed_handler: %s/%s", ev.path.nlri.addr, ev.path.nlri.length
        )
        # self.logger.info("_adj_rib_in_changed_handler: %s", ev.path.source)
        # self.logger.info(
        #     "_adj_rib_in_changed_handler: %s", ev.path._path_attr_map[2].value[0][0]
        # )
        pass

    @set_ev_cls(bgp_application.EventPeerDown)
    def _peer_down_handler(self, ev):
        self.logger.info("_peer_down_handler: Peer down: %s", ev)
        pass

    @set_ev_cls(bgp_application.EventPeerUp)
    def _peer_up_handler(self, ev):
        self.logger.info("_peer_up_handler: Peer up: %s", ev)
        pass
